import requests
import json
import urllib.parse
import time
from JsonFileHandler import JsonFileHandler
from collections import defaultdict
from BaiduPanRequest import BaiduPanRequest

target_dir = '/我的资源'

# 存储结果的变量
results = []
results_path_map = {}
results_par_path_map = defaultdict(list)
trans_list = []
trans_path_map = {}

def extract_sharelink(input_string):
    # 找到 'sharelink' 和 '-' 之间的字符串
    start_index = input_string.find('sharelink') + len('sharelink')
    end_index = input_string.find('-', start_index)
    return input_string[start_index:end_index]

baidu_pan_request = BaiduPanRequest(initFilePath='./baidu-trans/init.ini')
#trans_from ='397308849' 
trans_from = extract_sharelink(baidu_pan_request.root_dir)


# 替换root_dir中/为-
root_dir_path = baidu_pan_request.root_dir.replace('/', '-')
# 创建一个JsonFileHandler实例，指定要操作的JSON文件路径
json_file_handler = JsonFileHandler(f'data{root_dir_path}.json')
# 读取data.json到results
results = json_file_handler.read()
results_path_map = {data['path']: data for data in results}

trans_file_handler = JsonFileHandler(f'data{root_dir_path}.trans.json')
trans_list = trans_file_handler.read()
for item in trans_list:
    trans_path_map[item['path']] = item

# 遍历数据并进行分组,生成results_par_path_map
for item in results:
    path = item["path"]
    # 找出最后一个'/'的位置，以此来分割出父路径
    parent_path = path.rsplit('/', 1)[0] if '/' in path else path
    results_par_path_map[parent_path].append(item)

dir_check_cache = {}
def dir_check_or_create(dir):
    dir = target_dir + dir

    # 如果目录已经存在，直接返回
    if dir in dir_check_cache:
        return dir
    dir_check_cache[dir] = 1

    params = baidu_pan_request.getParams({"dir": f"{dir}", "order": "name", "desc": "0", "start": "0","limit": "10"})
    response = requests.get('https://pan.baidu.com/api/list', params=params, headers=baidu_pan_request.getHeaders())
    print(f'检查目录：{dir} 结果：{response.json()['errno']}')
    time.sleep(0.5)

    # 目录已存在，直接返回
    if response.json()['errno'] == 0:
        return dir
   
    data = {"path": f"{dir}", "isdir": "1", "size": "", "block_list": [],"method": "post","dataType": "json"}
    response = requests.post('https://pan.baidu.com/api/create', params=baidu_pan_request.getParams(params={"a": "commit"}), data=data, headers=baidu_pan_request.getHeaders())
    time.sleep(0.5)
    if response.status_code != 200:
        print("Error occurred while creating directory:", response.content)
        raise RuntimeError('Error occurred while creating directory')
    return dir

def remove_root_dir(dir):
    index = dir.find('/', 1)
    if index != -1:
        return dir[index:]
    return dir

def file_trans(dir):
    """
    对指定目录下的文件进行迁移
    """
    if dir not in results_par_path_map:
        print('没有找到对应的目录：', dir)
        return
    
    topath = None
    if results_path_map[dir]['isdir'] == 1:
       topath = dir_check_or_create(remove_root_dir(dir))
    else:
        return

    for node in results_par_path_map[dir]:
        if 'all_child_size' in node and node['all_child_size'] > 300:
            print('子总数超过300,遍历子目录：', node['path'])
            file_trans(node['path'])
        else:
            if node['path'] in trans_path_map:
                print('已经迁移过：', node['path'])
                continue
            params = baidu_pan_request.getParams({"from": trans_from, "ondup": "newcopy", "async":1})
            data = {"fsidlist": f"[{node['fs_id']}]", "path": f"{topath}", "types": 1}
            print('开始迁移：', node['path'], 'params: ', params, 'data: ', data)
            headers = baidu_pan_request.getHeaders({"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"})
            response = requests.post('https://pan.baidu.com/share/transfer', params=params, data=data, headers=headers)
            if response.json()['errno'] == 0:
                trans_list.append({"path": node['path'], "fs_id": node['fs_id'], "isdir": node['isdir']})
                trans_file_handler.write(trans_list)
            else:
                print('迁移失败：', response.text)
                raise RuntimeError('Error occurred while transferring file')
            time.sleep(2.1)
    
# 根据root_dir，遍历results_par_path_map，对每个节点判断迁移
file_trans(baidu_pan_request.root_dir_push)
